<template>
  <div class="tmpl">
    <!-- 头部标题行信息 -->
    <div class="page-title">
      <span>菜单</span><span class="page-title-en">MENU</span>
    </div>
    <!-- 正文信息 -->
    <div class="page-content">
      <!-- 表格上方右侧按钮组 -->
      <el-row class="btn-group-right">
        <el-button class="btn-group-right-item" type="primary" icon="el-icon-search"
          size="small" @click="search">搜索</el-button>
        <el-button class="btn-group-right-item" type="primary" icon="el-icon-plus"
          size="small" @click="add">新增</el-button>
        <el-button class="btn-group-right-item" type="default" icon="el-icon-download"
          size="small" @click="exportDefault">导出</el-button>
        <el-button class="btn-group-right-item" size="small" type="primary" :icon="expands ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" @click="handleExpands">
          {{ expands ? '收起' : '展开' }}
        </el-button>
      </el-row>
      <!-- 分页表格 -->
      <el-table
        v-if="refreshTable"
        ref="multipleTable"
        :data="tableData"
        v-loading="loading"
        element-loading-background="rgba(255, 255, 255, 0.2)"
        border
        tooltip-effect="dark"
        style="width: 96%; margin-left: 2%;"
        row-key="id"
        :header-cell-style="{background:'#53A8FF', color:'#fff'}"
        :default-expand-all="expands"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column prop="name" label="菜单名称" width="200"></el-table-column>
        <el-table-column label="图标" width="60">
          <template #default="{row}">
            <i :class="row.icon" style="font-size: 22px"></i>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="60"></el-table-column>
        <el-table-column prop="permission" label="权限标识" width="250"></el-table-column>
        <el-table-column prop="link" label="组件路径" width="150"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column prop="type" label="类型" width="70">
          <template #default="{row}">
            <el-tag :type="row.type === 12801001 ? '' : row.type === 12801002 ? 'warning' : 'info'" disable-transitions>
              {{ row.type === 12801001 ? '目录' : row.type === 12801002 ? '菜单' : '按钮' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="70">
          <template #default="{row}">
            <el-tag :type="row.status === 12781001 ? 'success' : 'danger'" disable-transitions>
              {{ row.status === 12781001 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <!--
        <el-table-column prop="deleteFlag" width="100" label="是否启用">
          <template #default="{row}">
            <el-switch
              v-model="row.enable"
              active-color="#53A8FF"
              @change="onSwitchChange(row)">
            </el-switch>
          </template>
        </el-table-column>
        -->
        <el-table-column prop="operation" label="操作">
          <template #default="{row}">
            <el-link style="margin-left:15px;" type="primary" :underline="false" @click="edit('edit', row)">
              <i class="el-icon-edit"></i>编辑
            </el-link>
            <el-link style="margin-left:15px;" type="primary" :underline="false" @click="edit('view', row)">
              <i class="el-icon-view"></i>查看
            </el-link>
            <el-link style="margin-left:15px;" type="primary" :underline="false" @click="openDeleteModal(row)">
              <i class="el-icon-delete"></i>删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="clearfix"></div>
    <div class="page-footer"></div>
    <!-- 新建编辑弹窗 -->
    <menu-dialog :dialogData="childData" :form="childForm" :options="childOptions"
      :centerDialogVisible="childVisible" v-on:handleEvent="childEvent" />
  </div>
</template>

<script>
import MenuDialog from '@/components/Common/Menu/MenuDialog.vue'
export default {
  name: 'Menu',
  components: {
    MenuDialog
  },
  data () {
    return {
      loading: false,
      searchData: {},
      tableData: [],
      // 是否默认展开：否
      expands: false,
      // 配合收起、展开显示表格
      refreshTable: true,
      multipleSelection: [],
      childData: {
        editTitle: '新增菜单',
        editType: 'add'
      },
      childForm: {},
      childOptions: [],
      childVisible: false
    }
  },
  created () {
    // 调用分页查询接口
    this.loadData()
  },
  mounted () {

  },
  methods: {
    // 分页查询接口
    loadData () {
      this.loading = true
      let obj = Object.assign({}, this.searchData, {currentPage: this.currentPage, pageSize: this.pageSize})
      // console.log(obj)
      this.$apis.queryMenuPage(obj).then(res => {
        if (res && res.code === '200') {
          this.tableData = res.result
          setTimeout(() => {
            this.loading = false
          }, 500)
        } else {
          console.log(res)
          this.$notify.error({
            title: '错误',
            message: res.message
          })
          this.loading = false
        }
      }).catch(err => {
        console.log(err)
        this.loading = false
        this.$notify.error({
          title: '错误',
          message: '请求异常'
        })
      })
    },
    // 分页查询搜索
    search () {
      this.loadData()
    },
    // 分页查询重置
    reset () {
      this.searchData = {}
      this.loadData()
    },
    // 改变分页数量
    handleSizeChange (val) {
      this.pageSize = val
      this.loadData()
    },
    // 改变当前页数
    handleCurrentChange (val) {
      this.currentPage = val
      this.loadData()
    },
    // 行多选事件
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 行点击事件触发多选的样式
    handleRowClick (val) {
      this.$refs.multipleTable.toggleRowSelection(val)
    },
    // 启用停用事件
    onSwitchChange (val) {
      // 启用停用会触发行点击事件，所以再次触发下抵消
      this.$refs.multipleTable.toggleRowSelection(val)
    },
    add () {
      this.childVisible = true
      this.childData = {
        editTitle: '新增菜单',
        editType: 'add'
      }
      // 新增场景配合子组件watch监听form赋值菜单类型的默认值为目录（暂废弃）
      // 新增场景默认上级菜单为根节点，菜单类型为目录
      this.childForm = { id: 0, parentId: -1, type: 12801001 }
      this.childOptions = this.packageOptions(this.tableData)
    },
    edit (type, row) {
      // 获取明细并且打开弹窗
      let id = row.id
      this.getById(id, type)
    },
    // 重新组装树形菜单，递归找到最后一层把children去掉，否则el-cascader异常
    packageOptions (data) {
      let arr = data.concat()
      // 根节点value=-1
      let rootData = { label: '根节点', value: -1, parentId: 0 }
      for (let i = 0; i < arr.length; i++) {
        // 第一项加入根节点
        if (i === 0 && arr[i].value !== 0) {
          arr.unshift(rootData)
        } else {
          if (!arr[i].children) {
            continue
          }
          if (arr[i].children.length < 1) {
            // 最后一级没有数据删除children
            delete arr[i].children
          } else {
            // children不为空时继续调用该方法
            this.packageOptions(arr[i].children)
          }
        }
      }
      return arr
    },
    // 导出Excel
    exportDefault () {
      this.loading = true
      let obj = this.searchData
      this.$apis.exportBrand(obj).then(res => {
        if (res.data.type === 'application/json') {
          this.$notify.error({
            title: '错误',
            message: '请求异常'
          })
        } else {
          const link = document.createElement('a')
          const blob = new Blob([res.data], { type: res.headers['content-type'] })
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          link.download = 'User.xlsx'
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          // 延迟1秒loading效果
          setTimeout(() => {
            this.loading = false
          }, 1000)
        }
      }).catch(err => {
        console.log(err)
        this.loading = false
        this.$notify.error({
          title: '错误',
          message: '请求异常'
        })
      })
    },
    // 父组件接收子组件的数据
    childEvent (data) {
      // console.log(data)
      // 关闭弹窗
      this.childVisible = false
      // 清空弹窗
      this.childForm = {}
      // 如果弹框中保存成功后，则刷新TABLE
      if (data.event && data.event === 'confirm') {
        this.loadData()
      }
    },
    // 明细查询接口
    getById (id, type) {
      this.$apis.getMenuById({ id: id }).then(res => {
        // console.log(res)
        if (res && res.code === '200') {
          // 弹出编辑弹窗，并且填充form
          this.childVisible = true
          this.childData = {
            editTitle: type === 'edit' ? '编辑菜单' : '查看菜单',
            editType: type
          }
          this.childForm = Object.assign({}, this.childForm, res.result)
          this.childOptions = this.packageOptions(this.tableData)
        } else {
          console.log(res)
          this.$notify.error({
            title: '错误',
            message: res.message
          })
        }
      }).catch(err => {
        console.log(err)
        this.loading = false
        this.$notify.error({
          title: '错误',
          message: '请求异常'
        })
      })
    },
    // 收起 OR 展开
    handleExpands () {
      if (this.expands) {
        this.refreshTable = false
        this.expands = false
        this.$nextTick(() => {
          this.refreshTable = true
        })
      } else {
        this.refreshTable = false
        this.expands = true
        this.$nextTick(() => {
          this.refreshTable = true
        })
      }
    }
  }
}
</script>

<style scoped>
  .tmpl {
    border-radius: 5px;
    height: 100%;
  }

  /* 填充el-table右侧滚动条上方表头未被填充的空白 */
  /deep/ .el-table th.gutter {
    background-color: #53A8FF !important;
  }

  /* 解决移动端下按钮组错位的问题 */
  .el-button+.el-button {
    margin-left: 0px;
  }

  /* 无分页所以底部留白 */
  .page-footer {
    width: 100%;
    height: 20px;
  }
</style>
